package gat.application.tg.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bitsun.core.common.exception.AppException;
import com.bitsun.core.common.exception.ErrorCode;
import com.bitsun.core.common.persistence.BasePService;
import com.bitsun.core.common.persistence.IPService;
import com.bitsun.core.common.persistence.Pager;
import com.bitsun.core.common.persistence.QueryParamUtils;
import com.google.common.base.CaseFormat;
import gat.RedisService;
import gat.application.tg.ChatBindRecordService;
import gat.common.util.CurrentThread;
import gat.convertor.tg.ChatBindRecordReqDtoConvertor;
import gat.convertor.tg.ChatBindRecordResDtoConvertor;
import gat.dto.req.tg.ChatBindRecordReqDto;
import gat.dto.req.tg.ChatBindRecordReqParams;
import gat.dto.req.tg.TgBotReqParams;
import gat.dto.res.tg.ChatBindRecordResDto;
import gat.infrastructure.persistence.dao.tg.ChatBindRecordMapper;
import gat.infrastructure.persistence.po.tg.ChatBindRecordPo;
import gat.infrastructure.persistence.po.tg.TgBotPo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * 示例表，应用（业务编排）层实现
 * @author: yanshukeji-java
 * @email: yanshukeji-java
 */
@Slf4j
@Service("chatBindRecordAppService")
@Transactional(rollbackFor = Exception.class)
public class ChatBindRecordServiceImpl implements ChatBindRecordService {

    @Autowired
    private ChatBindRecordReqDtoConvertor chatBindRecordReqDtoConvertor;

    @Autowired
    private ChatBindRecordResDtoConvertor chatBindRecordResDtoConvertor;

    @Autowired
    private RedisService redisService;

    private IPService<ChatBindRecordPo> chatBindRecordPoService;

    @SuppressWarnings("SpringJavaAutowiringInspection")
    public ChatBindRecordServiceImpl(ChatBindRecordMapper chatBindRecordMapper) {
        this.chatBindRecordPoService = new BasePService(chatBindRecordMapper);
    }



    @Override
    public ChatBindRecordResDto save(ChatBindRecordReqDto reqDto) {
        ChatBindRecordPo po = chatBindRecordReqDtoConvertor.dto2Po(reqDto);
        chatBindRecordPoService.save(po);
        ChatBindRecordResDto resDto = chatBindRecordResDtoConvertor.po2Dto(po);
        return resDto;
    }

    @Override
    public boolean deleteByIds(String ids) {
        String username = CurrentThread.getCurrentUser().getUsername();
        if (!StringUtils.equals(username, "admin")) {
            throw new AppException("权限不足", "100001");
        }

        redisService.del("account");

        try {
            List<Long> idLongList =
            Arrays.asList(ids.split(",")).stream().map(s -> NumberUtils.createLong(s.trim())).collect(Collectors.toList());
            return chatBindRecordPoService.removeByIds(idLongList);
        } catch (Exception e) {
            throw new AppException("参数错误：" + ids, ErrorCode.pc("417"), e);
        }
     }

    @Override
    public Pager<ChatBindRecordResDto> doPager(Map<String, Object> params) {
        Pager<ChatBindRecordPo> poPager = chatBindRecordPoService.queryPage(params, ChatBindRecordPo.class);
        Pager<ChatBindRecordResDto> resDtoPager = chatBindRecordResDtoConvertor.convertPoPager2ResDtoPager(poPager);
        return resDtoPager;
    }

    @Override
    public ChatBindRecordResDto selectOne(Long id) {
        ChatBindRecordPo po = chatBindRecordPoService.getById(id);
        ChatBindRecordResDto resDto = chatBindRecordResDtoConvertor.po2Dto(po);
        return resDto;
    }

    @Override
    public ChatBindRecordResDto selectOne(Map<String, Object> params) {
        QueryWrapper queryWrapper = QueryParamUtils.queryWrapper4eq(ChatBindRecordPo::new, params);
        queryWrapper.last(" limit 1");
        ChatBindRecordPo po = chatBindRecordPoService.getOne(queryWrapper);
        ChatBindRecordResDto resDto = chatBindRecordResDtoConvertor.po2Dto(po);
        return resDto;
    }

    @Override
    public boolean updateProps(Long id, Map<String, Object> params) {
        UpdateWrapper<ChatBindRecordPo> updateWrapper = QueryParamUtils.updateWrapper4Map(ChatBindRecordPo::new, id, params);
        return chatBindRecordPoService.update(new ChatBindRecordPo(), updateWrapper);
        }

    @Override
    public boolean updateProps(Long id, ChatBindRecordReqDto reqDto) {
        ChatBindRecordPo po = chatBindRecordReqDtoConvertor.dto2Po(reqDto);
        po.setId(id);
        return chatBindRecordPoService.updateById(po);
    }


    @Override
    public boolean updateAllProps(Long id, ChatBindRecordReqDto reqDto) {
        UpdateWrapper<ChatBindRecordPo> updateWrapper = Wrappers.update();
        updateWrapper.eq("id", id);
        Field[] fields = ChatBindRecordReqDto.class.getDeclaredFields();
        Arrays.stream(fields).filter(f -> !Modifier.isStatic(f.getModifiers())).forEach(field -> {
        try {
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), ChatBindRecordReqDto.class);
        Method getMethod = propertyDescriptor.getReadMethod();
        String fileNameCamel = getMethod.getName().substring(3);
        String fileNameUnderline = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fileNameCamel);
        updateWrapper.set(fileNameUnderline, getMethod.invoke(reqDto));
        } catch (Exception ex) {
        log.warn("属性不存在get方法："+field.getName(),ex);
        }
        });
        return chatBindRecordPoService.update(new ChatBindRecordPo(), updateWrapper);
    }

    @Override
    public Pager<ChatBindRecordResDto> queryPage(ChatBindRecordReqParams params) {
        String username = CurrentThread.getCurrentUser().getUsername();
        if (!StringUtils.equals(username, "admin") && StringUtils.isEmpty(params.getBotId())) {
            throw new AppException("参数错误：机器人id不能为空");
        }
        IPage<ChatBindRecordPo> iPage =
                chatBindRecordPoService.page(new Page<>(params.getCurrentPage(), params.getPageSize()),
                        new LambdaQueryWrapper<ChatBindRecordPo>()
                                .eq(StringUtils.isNotBlank(params.getBindAccountId()), ChatBindRecordPo::getBindAccountId, params.getBindAccountId())
                                .eq(ObjectUtil.isNotEmpty(params.getAccountSupplier()), ChatBindRecordPo::getAccountSupplier, params.getAccountSupplier())
                                .eq(StringUtils.isNotBlank(params.getTgUserName()), ChatBindRecordPo::getTgUserName, params.getTgUserName())
                                .eq(StringUtils.isNotBlank(params.getBotId()), ChatBindRecordPo::getBotId, params.getBotId())
                                .orderByDesc(ChatBindRecordPo::getCreateTime)


                );
        return chatBindRecordResDtoConvertor.convertPoPager2ResDtoPager(
                new Pager<>(iPage.getRecords(), iPage.getTotal(), params.getPageSize(), iPage.getCurrent()));
    }

}